package com.system.insurance.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.system.common.config.exception.CustomException;
import com.system.common.result.Result;
import com.system.insurance.entity.User;
import com.system.insurance.service.UserService;
import com.system.insurance.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 后台用户账号信息 前端控制器
 * </p>
 *
 * @author WS
 * @since 2024-05-10
 */
@RestController
@Api(tags = "后台用户")
@RequestMapping("/insurance/user")
public class UserController {


    @Autowired
    private UserService userService;

    @ApiOperation("用户账号分页查询")
    @GetMapping("{page}/{limit}")
    public Result index(@PathVariable Long page,
                        @PathVariable Long limit,
                        User user) {
        //封装数据页数  每页数量
        Page<User> userPage = new Page<>(page, limit);
        //筛选条件
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper();

//        String userName = user.getAccount();
//        //模糊查询
//        if (!StringUtils.isEmpty(userName)) {
//            wrapper.like(User::getAccount, userName);
//        }
//        //eq  大于等于
//        if (!StringUtils.isEmpty(createTimeBegin)){
//            wrapper.eq(SysUser::getCreateTime,createTimeBegin);
//        }
//        //lt  小于等于
//        if (!StringUtils.isEmpty(createTimeEnd)){
//            wrapper.lt(SysUser::getCreateTime,createTimeEnd);
//        }

        Integer id = user.getId();
        if (id!=null) {
            if (id!=null){
                wrapper.eq(User::getId,id);
            }
        }
        IPage<User> uPage = userService.page(userPage, wrapper);
        return Result.ok(uPage);
    }

    @ApiOperation(value = "获取用户")
    @GetMapping("get/{id}")
    public Result get(@PathVariable Integer id) {

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getId,id);
        User user = userService.getById(id);
        if (user!=null) {
            return Result.ok(user);
        }
        return Result.fail().message("没有该用户！");
    }

    @ApiOperation(value = "添加用户")
    @PostMapping("save")
    public Result<User> save(@RequestBody User user) {
        //对密码进行加密
//        String encrypt = MD5.encrypt(password);
//        user.setPassword(encrypt);
        user.setAccount(user.getAccount());
        String password = user.getPassword();
        user.setPassword(password);
        user.setCreateTime(LocalDateTime.now());
        userService.save(user);
        return Result.ok(user).message("添加成功");
    }



    @ApiOperation(value = "更新用户")
    @PutMapping("update")
    public Result<User> updateById(@RequestBody User user) {

        user.setUpdateTime(LocalDateTime.now());
        boolean b = userService.updateById(user);
        if (!b){
            return Result.fail(user).message("更新失败");
        }
        return Result.ok(user).message("更新成功");
    }

    @ApiOperation(value = "删除用户")
    @DeleteMapping("remove/{id}")
    public Result remove(@PathVariable Integer id) {
        boolean byId = userService.removeById(id);

        if (!byId){
            return Result.fail().message("删除失败");
        }
        return Result.ok().message("删除成功");
    }

    @ApiOperation(value = "批量删除用户")
    @DeleteMapping("remove")
    public Result remove(@RequestBody List<User> users) {

        if (users != null && users.size() > 0) {
            for (User user : users) {
                userService.removeById(user.getId());
                return Result.ok();
            }
        }
        return Result.fail();
    }

    /*
//     * @description: 用户的登录
//     * @param: User user
//     * @return:result
//     */
//    @PostMapping("/login")
//    public Result login(@RequestBody User user, HttpSession httpSession, HttpServletResponse response) throws UnsupportedEncodingException {
//        String checkCode = (String) httpSession.getAttribute("checkCode");
//        System.out.println(checkCode);
//        if (user.getCheckCode() == null || !user.getCheckCode().equalsIgnoreCase(checkCode)) {
//            return Result.fail().message("登陆失败");
//        }
//
//            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
//            wrapper.eq(User::getAccount,user.getAccount()).
//                    eq(User::getPassword,user.getPassword());
//            User one = userService.getOne(wrapper);
//            if (one!=null) {
//                JwtUtil jwtUtil = new JwtUtil();
//                String token = jwtUtil.getToken(one);
//                Cookie cookie = new Cookie("account", user.getAccount());
//                cookie.setMaxAge(60 * 60 * 24 * 7);
//                cookie.setPath("/");
//                response.addCookie(cookie);
//                httpSession.setAttribute("account", user.getAccount());
//                return Result.ok(user).message("登陆成功");
//            } else if (one.getAccount()==null || one.getAccount()=="") {
//                return Result.fail(user).message("登陆失败,用户不存在");
//            } else {
//                return Result.fail(user).message("登陆失败");
//            }
//        }

    @ApiOperation(value = "登录用户")
    @PostMapping("/login")
    public Result login(@RequestBody User loginVo) {
        String username = loginVo.getAccount();
        //2.去数据库查询
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getAccount, username);
        User one = userService.getOne(wrapper);
        if (null == one) {
            throw new CustomException(201, "用户不存在");
        }
//        if(!MD5.encrypt(loginVo.getPassword()).equals(sysUser.getPassword())) {
//        throw new CustomException(201,"密码错误");
//    }
        if (!loginVo.getPassword().equals(one.getPassword())) {
            throw new CustomException(201, "密码错误");
        }

        Map<String, Object> cliams = new HashMap<>();
        cliams.put("id",one.getId());
        String token = JwtUtils.generateJwt(cliams);

        return Result.ok(token).message("登陆成功");
    }

    /**
     * 退出
     *
     * @return
     */
    @PostMapping("/logout")
    public Result logout() {
        return Result.ok();
    }

}

